<template>
  <div class="mform">
    <div class="back">
      <Back>
        <div class="form-btn">
          <el-button type="primary" @click="save()">保存</el-button>
        </div>
      </Back>
    </div>
    <div class="form-content">
      <div class="form-box" style="width: 60%;">
        <el-form ref="formRef" :model="form" :rules="rules" :label-position="'left'" label-width="auto">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" clearable />
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="form.account" placeholder="请输入账号" clearable />
          </el-form-item>

          <el-form-item label="密码">
            <el-input v-model="form.pass" type="password" placeholder="请输入密码" clearable />
          </el-form-item>

          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" placeholder="">
              <el-option :value="item.id.toString()" :label="item.name" v-for="(item, index) in roleList" :key="index" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script setup name="AdminDetail">
const { proxy } = getCurrentInstance()

const formRef = ref();
const roleList = ref([]);
const form = reactive({ id: '', parent: null, name: '', key: '', icon: '', route: '', component: '', type: '1', mode: '1', sort: '0', desc: '' });
//验证规则
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
};
//保存
async function save() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      let res = await proxy.$post('adminSave', form)
      if (res.code === 0) {
        ElMessage({ type: 'success', message: '保存成功' });
        proxy.$bus.emit('back');
      }
    }
  });
}

onMounted(() => {
  getRole()
  // 编辑
  let id = proxy.$route.query.id || null;
  if (id) {
    getDetail(id)
  }
});

async function getRole() {
  let res = await proxy.$get('adminRoleList', {
    page: 1,
    page_size: 1000,
  }, false)
  if (res.code === 0) {
    roleList.value = res.data.list || []
  }
}

async function getDetail(id) {
  let res = await proxy.$post('adminDetail', {
    id
  }, false)
  if (res.code === 0) {
    Object.assign(form, res.data);
  }
}
</script>
<style scoped lang="scss"></style>
